/*
 *Copyright(c) 2021 Shenzhen Kaihong Digital Industry DevelopmentCo.,Ltd
 *Licensed under the Apache License,Version2.0(the"License");
 *you may not use this file except in compliance with the License.
 *You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,software
 * distributed under the License is distributed on an "AS IS"BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.chinasoft.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TokenUtils {
    //设置过期时间7有效
    private static final long APP_EXPIRE_DATE=1000*60*60*24*7;
    private static final long BACK_EXPIRE_DATE=1000*60*30*24*7;
    //token秘钥
    private static final String TOKEN_SECRET = "HOJM34NJE98GQHJK3PMGD988WJZK8";

    public static String token (String username,String userId,String type){
        Date date=null;
        String token = "";
        try {
            //过期时间
            if (type.equals("back")){
                  date = new Date(System.currentTimeMillis()+BACK_EXPIRE_DATE);
            }
            if (type.equals("app")){
                  date = new Date(System.currentTimeMillis()+APP_EXPIRE_DATE);
            }
            //秘钥及加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            //设置头部信息
            Map<String,Object> header = new HashMap<>();
            header.put("type","JWT");
            header.put("alg","HS256");
            //携带username，password信息，生成签名
            token = JWT.create()
                    .withHeader(header)
                    .withClaim("username",username)
                    .withClaim("loginUserId",userId).withExpiresAt(date)
                    .sign(algorithm);
        }catch (Exception e){
            e.printStackTrace();
            return  null;
        }
        return token;
    }

    public static DecodedJWT verify(String token){
        /**
         * @desc   验证token，通过返回true
         * @params [token]需要校验的串
         *
         **/

        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt;
        }catch (Exception e){
            e.printStackTrace();
            return  null;
        }
    }


}
